import { reactive, onMounted, defineComponent, toRefs, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import saleApi from '@/api/sale/sale-api'
import warehouseApi from '@/api/inwarehouse/warehouse-api'
import projectApi from '@/api/inwarehouse/project-api'
import goodsApi from '@/api/inwarehouse/goods-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
import deliveryApplyApi from '@/api/sale/deliveryApply-api'

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const statusOptions = [
      { value: '0', label: '新建' },
      { value: '99', label: '已完成' },
      { value: '100', label: '已同步' },
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '销售单',
      api: saleApi,
      columns: [
        { prop: 'projectName', label: '项目', valueType: 'input' },
        { prop: 'projectOriginalNo', label: '合同号', valueType: 'input' },
        { prop: 'status', label: '状态', valueType: 'select', options: statusOptions, slot: true },
        { prop: 'createOn', label: '日期', slot: true },
        { prop: 'operation', label: '操作', slot: true }
      ],
      rules: {
        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }],
        status: [{ required: true, message: '请输入状态', trigger: 'blur' }],
      },
      other: {
        formatDt(val) {
          if (!val) {
            return '-'
          }
          return val.substring(0, 10)
        },
        async pass() {
          ctx.editData.status = '99';
          const res = await saleApi.save(ctx.editData);
          if(res.success) {
            ElMessage.success('审核成功');
            ctx.loadData();
            ctx.editVisible = false;
          }
        },
        async selectGoods() {
          if(!data.delGoodsList || data.delGoodsList.length === 0) {
            ElMessage.warning('未选择产品数据');
            return
          }
          const {
            projectId,
            projectName,
            projectOriginalNo
          } = ctx.editData
          const goodsArr = []
          data.delGoodsList.map(item => {
            const obj = {...item};
            delete obj['id'];
            goodsArr.push(obj)
          })
          const params = {
            projectId,
            projectName,
            projectOriginalNo,
            status: '0',
            orderGoodsList: goodsArr
          }
          ElMessageBox.confirm(`确认选择数据生成发货申请单？`, '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true
          })
            .then(async () => {
              const res = await deliveryApplyApi.save(params)
              if (res.success) {
                ElMessage.success('生成发货申请单成功');
                ctx.editVisible = false;
              }
            })
            .catch()
        },
        handleproject(val: string) {
          const obj = data.projectOptions.find(item => {
            return item.id === val
          })
          ctx.editData.projectName = obj['name']
          ctx.editData.projectOriginalNo = obj['originalNo']
        },
        getStatusName(val: string) {
          if (!val) {
            return '-'
          }
          return statusOptions.find(item => {
            return item.value === val
          }).label
        },
        addGoods() {
          if (!ctx.editData['orderGoodsList']) {
            ctx.editData['orderGoodsList'] = []
          }
          ctx.editData['orderGoodsList'].push({})
        },
        delGoods() {
          data.delGoodsList.map(dgl => {
            const index = ctx.editData['orderGoodsList'].findIndex(item => {
              return item.id === dgl.id
            })
            ctx.editData['orderGoodsList'].splice(index, 1)
          })
        },
        handleGoodsSelectionChange(val: any) {
          if (!ctx.editData['orderGoodsList']) {
            return
          }
          data.delGoodsList = val
        },
        handleGoodsChange(val: string) {
          const obj = data.goodsOptions.find(item => {
            return item.skuName === val
          })
          const index = ctx.editData['orderGoodsList'].findIndex(item => {
            return item.skuName === val
          })
          ctx.editData['orderGoodsList'].splice(index, 1, obj)
        }
      }
    }))

    const getGoodsList = async (val: string) => {
      data.getGoodsLoading = true
      const params = { otherFilter: { skuName: val } }
      const res = await goodsApi.list(params)
      data.goodsOptions = res.data.records
      data.getGoodsLoading = false
    }

    const getProjectList = async () => {
      const params = { filter: { disabled: 2 } }
      const res = await projectApi.list(params)
      data.projectOptions = res.data.records
    }


    const data = reactive({
      ctx,
      statusOptions,
      projectOptions: [],
      goodsOptions: [],
      getGoodsLoading: false,
      delGoodsList: [],
      getGoodsList
    })

    // init
    onMounted(() => {
      getProjectList()
      // getWarehouseList()
      ctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
